<template>
    <CommonPage ref="channelProductRef" :tableConfig="option" formKey="channelProduct"></CommonPage>
    <ElDialog v-model="dialog" width="600px" :title="title">
        <UiForm v-if="dialog" :formData="formData" @close="dialog = false" @callback="submitForm"/>
    </ElDialog>
</template>
<script setup>
import CommonPage from '@/components/CommonPage/index.vue'
import UiForm from '@/components/uiForm.vue'
import {ElDialog,ElMessage, ElMessageBox, ElLoading } from 'element-plus'
import { ref, reactive, computed } from 'vue';
import {cascaderAddress} from '../../utils/addressData';
import {getProductList} from '@/server/manage/product.js'
import {getChannelList, getAgreementList,setChannelproduct,getChannelproducInfo,channelProductChangeStatus,deleteChannelProduct} from '@/server/manage/channel.js'
import { validateMobile } from '@/utils/validate'
import {waitFiles} from "@/utils"

const dialog = ref(false)
const openType = ref()
const rowInfo = ref()
const statusOption = [
    {label: '启用', value: '1'},
    {label: '停用', value: '0'}
]
const products = ref([])
const channels = ref([])
const agreements = ref([])
const channelProduct = ref()
const channelProductRef = ref()
let channelProductId = null
const option = reactive({
    operationWidth: 200,
    formItems: [
        {label: '渠道名称', prop: 'channelName', type: 'input', show: true},
        {label: '联系人', prop: 'contacts', type: 'input', show: true},
        {label: '状态', prop: 'status', type: 'select', show: true, options: statusOption},
    ],
    buttons: [
        {label: "新增", icon: 'Plus', auth: '', handle: (event)=> {handleOpen('add')}},
        {label: "删除", icon: 'Delete', type: 'danger', handle: (event)=> {handleDel(event)}},
    ],
    options: [
        {label: '停用', handle: (event) => {handleStatus(event, 0)}, isShow:(row) => {return row.status == 1}, type: "warning"},
        {label: '启用', handle: (event) => {handleStatus(event, 1)}, isShow:(row) => {return row.status == 0}, type: "success"},
        {label: '编辑', handle: (event) => {handleOpen('edit', event)}, isShow:() => {return true}},
        {label: '删除', handle: (event) => {handleDel(event)}, isShow:() => {return true}, type: 'danger'}
    ]
})
// 新增的表单参数
const formData = reactive([
    {label: "渠道名称", type: 'select', key: "channelId", value: '', required: true, options: channels},
    {label: "产品名称", type: 'select', key: "productId", value: '', required: true, options: products},
    {label: "授权协议", type: 'select', key: "agreeIds", value: '', required: true, placeholder:'请选择授权协议（授权协议支持多选）', multiple: true, options: agreements},
    {label: "地区", type: 'cascader', key: "areaCode", value: '', required: true, cascaderOptions: cascaderAddress()},
    {label: "二维码", type: 'uploadFile', key: "qrCodeUrl", value: [], required: true, fileType: ['png', 'jpg', 'jpeg'], fileSize: 10},
    {label: "联系人", type: 'input', key: "contacts", value: '', required: true },
    {label: "联系电话", type: 'input', key: "contactTel", value: '', required: true, rules: { validator: validateMobile, trigger: 'blur' } },
    {label: "状态", type: 'radio', key: "status", value: '', required: true, options: statusOption},
    {label: "备注", type: 'input', key: "remark", widgetType: 'textarea', value: '', required: false}
])
const title = computed(() => {
    let obj = {add: '新增',edit: '编辑' }
    return obj[openType.value]
})
// 修改状态
const handleStatus = (row, status) => {
    channelProductChangeStatus(row).then(res => {
        channelProductRef.value.resetTableData()
        ElMessage({ message: "操作成功！", type: 'success'})
    })
}
// 编辑赋值
const getDetail = (item) => {
    getChannelproducInfo(item.id).then(res => {
        let data = res.channelProductInfo
        formData.forEach(next => {
            next.value = data[next.key]
            if(next.key === "areaCode") {next.value = data.areaCode.split("/")}
            if(next.key === "qrCodeUrl") {next.value = data.qrCodeUrl.split("^/").map(url => {
                return {url: url, type: "string"}
            })}
        })
    })
    channelProductId = item.id
}
// 新增 编辑
const handleOpen = (type, item) => {
    channelProductId = null
    if(item) getDetail(item)
    else formData.forEach(next => next.value = "")
    openType.value = type
    dialog.value = true
}
// 提交
const submitForm = async(formData) => {
    let obj = {add: 'save',edit: 'update' }
    let params = JSON.parse(JSON.stringify(formData))
    const loading = ElLoading.service({ lock: true, text: '提交中，请稍等！', background: 'rgba(0, 0, 0, 0.7)',})
    let urls = await waitFiles(formData.qrCodeUrl)
    params.areaCode = formData.areaCode.join('/')
    params.qrCodeUrl = urls.join('^/')
    if(channelProductId){ params.id = channelProductId}
    setChannelproduct(params, obj[openType.value]).then(res => {
        loading.close()
        dialog.value = false
        channelProductRef.value.resetTableData()
        ElMessage({ message: "操作成功！", type: 'success'})
    }).catch(msg => {loading.close()})
}
// 获取产品列表
const getProduct = () => {
    getProductList({limit: "9999",page: "1",productStatus: "2"}).then(res => {
        products.value = res.page.list.map(item => {
            return {label: item.productName, value: item.id}
        })
    })
}
// 渠道信息
const getChannel = () => {
    getChannelList({limit: "9999",page: "1",dataStatus: "1"}).then(res => {
        channels.value = res.page.list.map(item => {
            return {label: item.channelName, value: item.id+""}
        })
    })
}
// 获取协议列表
const getAgreement = () => { 
    getAgreementList({limit: "9999",page: "1",status: "1"}).then(res => {
        agreements.value = res.page.list.map(item => {
            return {label: item.agreementName, value: item.id}
        })
    })
}
//删除
const handleDel = (list) => {
    let ids = Array.isArray(list) ? list.map(item => item.id) : [list.id]
    ElMessageBox.confirm('您确定删除吗？','提示',
        {confirmButtonText: '确定',cancelButtonText: '取消',type: 'warning',}
    ).then(() => {
        deleteChannelProduct(ids).then(res => {
            channelProductRef.value.resetTableData()
            ElMessage({ type: 'success', message: '删除成功！'})
        })
    })
    .catch()
}
// 初始化
const init = () => {
    getProduct()
    getChannel()
    getAgreement()
}
init()
</script>